﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Staticage.Core {
    public class XmlConfiguration : FileConfiguration {
        XDocument document;
        XElement section;

        public XmlConfiguration(string filePath)
            : base(filePath) {
            document = XDocument.Load(this.filePath);
            this.section = document.Element(defaultSectionName);
        }

        public override IConfiguration Select(string section) {
            this.section = document.Element(section);
            return this;
        }

        public override string GetValue(string key) {
            XElement element = section.Element(key);
            return element == null ? string.Empty : element.Value;
        }

        public override IConfiguration SetValue(string key, object value) {
            if (section.Element(key) == null)
                section.Add(new XElement(key, value));
            else
                section.Element(key).SetValue(value.ToString());
            return this;
        }

        public override IConfiguration Save() {
            document.Save(this.filePath);
            return this;
        }
    }
}
